package com.feifan.common.utils.send;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 发送短信
 * @author: 非凡
 * @create: 2020-07-25 19:35
 **/
@Component
public class SendSms {


    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.secret}")
    private String secret;

    public Boolean send(String phoneNum, String templateCode, HashMap<Object, Object> code) {

        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 自定义参数（手机号，验证码，签名，模板）
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "OA自动化办公系统");
        request.putQueryParameter("TemplateCode", templateCode);

        try {
            // Map集合转Json
            ObjectMapper jacksonMapper = new ObjectMapper();
            request.putQueryParameter("TemplateParam", jacksonMapper.writeValueAsString(code));

            // 返回结果
            CommonResponse response = client.getCommonResponse(request);

            System.out.println("阿里请求响应 - "+response.getData());

            return response.getHttpResponse().isSuccess();
        } catch (JsonProcessingException | ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

}
